package edu.rit.teamrocket.view;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;

import javax.swing.*;

import edu.rit.teamrocket.controller.FoodController;

public class NewEntry extends JFrame
{
	private JPanel panel1, panel2, panel3;
	private JLabel weight, date;
	private JTextField text;
	private JButton add, cancel;
	private JComboBox day, month, year;
	private JFrame parent, frame;
	private FoodController controller;

	public NewEntry(final JFrame parent)
	{
		super("New Entry");

		this.parent = parent;
		this.frame = this;
		this.controller = new FoodController();

		weight = new JLabel("Weight: ");
		date = new JLabel("Date: ");
		text = new JTextField(10);
		add = new JButton("Add");
		cancel = new JButton("Cancel");
		String[] comboBoxDay = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"};
		String[] comboBoxMonth = {"1","2","3","4","5","6","7","8","9","10","11","12"};
		String[] comboBoxYear = {"2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014"};

		day = new JComboBox(comboBoxDay);
		month = new JComboBox(comboBoxMonth);
		year = new JComboBox(comboBoxYear);

		panel1 = new JPanel();
		this.add(panel1, BorderLayout.NORTH);
		panel1.add(weight);
		panel1.add(text);

		panel2 = new JPanel();
		this.add(panel2, BorderLayout.CENTER);
		panel2.add(date);
		panel2.add(day);
		panel2.add(month);
		panel2.add(year);

		panel3 = new JPanel();
		this.add(panel3, BorderLayout.SOUTH);
		panel3.add(add);
		panel3.add(cancel);

		add.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent arg0)
			{
				if (validateInput(text.getText())) {
					controller.addLog(Double.parseDouble(text.getText()), 
										Integer.parseInt((String) day.getSelectedItem()),
										Integer.parseInt((String) month.getSelectedItem()),
										Integer.parseInt((String) year.getSelectedItem()));
					frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
					parent.setVisible(true);
					
				}
				else JOptionPane.showMessageDialog(null, "Please enter a numeric value.", "Incorrect weight", JOptionPane.ERROR_MESSAGE);
			}
		});
		
		cancel.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent arg0)
			{
				frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
				parent.setVisible(true);
			}
		});

		this.setVisible(true);
		this.pack();
	} 
	
	public boolean validateInput(String input)
	{
		return input.matches("-?\\d+(\\.\\d+)?");
	}
}
